<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;
use app\common\service\Media;
use app\common\service\Tenant as TenantService;
use plugin\wechat\app\model\BotReply as ReplyM;
use plugin\wechat\app\service\BotReply as ReplyService;
use plugin\wechat\app\service\Bot as BotService;
use plugin\wechat\app\service\BotGroup as GroupService;
use plugin\wechat\app\service\BotFriend as FriendService;
use Support\Request;

class Botreply extends BotBase
{
    /**
     * @var ReplyM
     */
    protected $model;
    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new ReplyM();
    }

    private function tabList(){
        $tab_list = [];
        $events = ReplyService::events();
        foreach ($events as $k => $v){
            $tab_list[$k] = [
                'title' => $events[$k],
                'href' => url('index', ['event' => $k])
            ];
        }
        return $tab_list;
    }

    /**
     *
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function copy()
    {
        $bot = \request()->botInfo;
        if(request()->isPost()){
            $post_data = input('post.');
            $exists = $this->model->where([
                $this->tenantWhere(),
                ['bot_id' ,'=', $bot['id']]
            ])->column('media_id');

            $list = $this->model->where([
                $this->tenantWhere(),
                ['bot_id' ,'=', $post_data['bot_id']],
                ['status','=', 1],
                ['media_id' ,'notin', count($exists) ? $exists : [0]]
            ])->select();
            foreach ($list as $v){
                unset($v['id']);
                $v['bot_id'] = $bot['id'];
                $v['wxids'] = '';
                $this->model->createOne($v);
            }
            return $this->success('操作成功！', '');
        }
        $bot_list = BotService::getIdToTitle(null, [['id', '<>', $bot['id']]]);
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('复制内容')
            ->setPostUrl(url('copy'))
            ->addFormItem('bot_id', 'chosen', '机器人', '请选择', $bot_list, 'required');

        return $builder->show();
    }

    /**
     * 移除回复内容
     * @return \support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function delPost(){
        $bot = \request()->botInfo;
        $id = input('id', 0);
        $where = [
            $this->tenantWhere(),
            ['bot_id','=', $bot['id']],
            ['id', '=', $id]
        ];
        $reply = $this->model->where($where)->find();
        if(empty($reply)){
            return $this->error('参数错误!');
        }

        if($this->model->where($where)->delete()){
            $where = [
                ['bot_id' , '=', $bot['id']],
                ['event', '=', $reply['event']],
                ['status' , '=', 1]
            ];
            !empty($reply['msg_type']) && $where[] = ['msg_type', '=', $reply['msg_type']];
            ReplyService::getReplies($where, true);
            return $this->success('操作成功!');
        }
        return $this->error('操作失败!');
    }
    public function index(){
        $bot = \request()->botInfo;
        $current_name = input('event', ReplyService::BEADDED);
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['bot_id' ,'=', $bot['id']],
                [ 'event' ,'=', $current_name]
            ];
            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('sort', 'desc')
                    ->select();

                foreach ($list as $k => $v){
                    if($v['media_id']){
                        $media = Media::getModel($v['media_type'])->where([
                            $this->tenantWhere(),
                        ])->find($v['media_id']);
                        $v = array_merge($media->toArray(), $v->toArray());
                    }
                    $list[$k] = $v;
                }
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setTabNav($this->tabList(), $current_name)
            ->setDataUrl(url('index', ['event' => $current_name]))
            ->addTopButton('addnew', ['text' => '新增消息响应', 'title' => '新增消息响应','href' => url('add', ['event' => $current_name])])
            ->addTableColumn(['title' => '响应类型', 'field' => 'handle_type', 'type' => 'enum','options'=>ReplyService::handleTypes(),'minWidth' => 80])
            ->addTableColumn(['title' => '内容类型', 'field' => 'media_type', 'type' => 'enum','options'=>Media::types(),'minWidth' => 80])
            ->addTableColumn(['title' => '名称', 'field' => 'title', 'minWidth' => 80]);
        switch ($current_name){
            case Media::IMAGE:
                $builder->addTableColumn(['title' => '图片', 'field' => 'url', 'minWidth' => 100]);
                break;
            case Media::FILE:
                $builder->addTableColumn(['title' => '文件', 'field' => 'url', 'minWidth' => 200]);
                break;
            case Media::VIDEO:
                $builder->addTableColumn(['title' => '视频', 'field' => 'url', 'minWidth' => 200]);
                break;
            default:
                $builder->addTableColumn(['title' => '内容', 'field' => 'content', 'minWidth' => 200]);
                break;
        }
        $builder->addTableColumn(['title' => '优先级', 'field' => 'sort', 'minWidth' => 80])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'minWidth' => 80,'type' => 'enum','options' => [0 => '禁用', 1=> '启用']])
            ->addTableColumn(['title' => '操作', 'minWidth' => 150, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('delete', ['text'=>'移除', 'href'=>url('delPost', ['id' => '__data_id__'])]);

        if($current_name == ReplyService::MSG){
            $builder->addTopButton('addnew', ['text' => '新增动作响应', 'title' => '新增动作响应','href' => url('eventAdd', ['event' => $current_name])]);
        }
        return $builder->show();
    }

    public function savePost(Request $request, $jump_to = '', $data = [])
    {
        $bot = $request->botInfo;
        $post_data = input('post.');
        if(isset($post_data['media_id']) && empty($post_data['media_id'])){
            return $this->error('请选择素材!', '', ['token' => token()]);
        }

        if(empty($post_data[$this->pk])){
            $post_data['company_id'] = TenantService::getCompanyId();
            $res = $this->model->createOne($post_data);
        }else {
            $res = $this->model->update($post_data);
        }

        if($res){
            $where = [
                ['bot_id' , '=', $bot['id']],
                ['event', '=', $res['event']],
                ['status' , '=', 1]
            ];
            isset($res['msg_type']) && $where[] = ['msg_type', '=', $res['msg_type']];
            ReplyService::getReplies($where, true);
            return $this->success('数据保存成功', $jump_to);
        }else{
            return $this->error('操作失败！');
        }
    }

    /**
     * 编辑消息响应
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function edit(){
        $bot = \request()->botInfo;
        $id = input('id', null);
        $reply = $this->model->where([
            $this->tenantWhere(),
            ['bot_id','=',$bot['id']]
        ])->find($id);

        if (!$reply) {
            return $this->error('参数错误!');
        }

        if($reply['event'] == ReplyService::MSG && $reply['handle_type'] != ReplyService::HANDLE_MSG){
            return $this->redirect(url('eventEdit', ['id' => $id]));
        }

        $material = Media::getModel($reply['media_type'])->where([
            $this->tenantWhere(),
            ['id' ,'=', $reply['media_id']]
        ])->find();
        if(!empty($reply['wxids'])){
            $reply['wxids'] = explode(',', $reply['wxids']);
        }

        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->setFormData($reply);
        switch ($reply['event']){
            case ReplyService::FRIEND_IN:
                $groups = GroupService::getWxidToNickname();
                $builder->addFormItem('wxids', 'chosen_multi', '指定群', '指定群', $groups, 'required')
                    ->addFormItem('need_at', 'radio', '艾特新人', '艾特新人', [0 => '否', 1 => '是'], 'required');
                break;
            case ReplyService::MSG:
                $builder->addFormItem('msg_type', 'select', '消息类型', '接收到的消息类型', BotService::msgTypes())
                    ->addFormItem('wxids', 'chosen_multi', '指定对象', '指定对象', FriendService::getWxidToNickname(), 'required');
                break;
        }
        return $builder->addFormItem('media', 'choose_media', '回复内容', '回复内容', ['types' => Media::types(), 'id' => $reply['media_id'], 'type' => $reply['media_type']], 'required')
            ->addFormItem('sort', 'number', '排序', '排序', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'], 'required')
            ->show(['material' => $material]);
    }

    /**
     * 新增消息响应
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function add(){
        $bot = \request()->botInfo;
        $current_name = input('event', ReplyService::BEADDED);
        $builder = new FormBuilder();
        $material = [];

        $data = [
            'bot_id' => $bot['id'],
            'event' => $current_name,
            'status' => 1,
            'handle_type' => ReplyService::HANDLE_MSG,
            'sort' => 1
        ];
        $builder->setPostUrl(url('savePost'))
            ->setTip("添加【".ReplyService::events($current_name)."】回复")
            ->addFormItem('bot_id', 'hidden', 'botid', 'botid')
            ->addFormItem('event', 'hidden', 'event', 'event')
            ->addFormItem('handle_type', 'hidden', 'handle_type', 'handle_type');

        switch ($current_name){
            case ReplyService::FRIEND_IN:
                $data['need_at'] = 0;
                $groups = GroupService::getWxidToNickname();
                $builder->addFormItem('wxids', 'chosen_multi', '指定群', '对指定群起作用', $groups, 'required')
                    ->addFormItem('need_at', 'radio', '艾特新人', '艾特新人', [0 => '否', 1 => '是'], 'required');
                break;
            case ReplyService::MSG:
                $builder->addFormItem('msg_type', 'select', '消息类型', '接收到的消息类型', BotService::msgTypes())
                    ->addFormItem('wxids', 'chosen_multi', '指定对象', '指定对象', FriendService::getWxidToNickname(), 'required');
                break;
        }
        return $builder->addFormItem('media', 'choose_media', '回复内容', '回复内容', ['types' => Media::types()], 'required')
            ->addFormItem('sort', 'number', '排序', '数字越大优先级越高', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'], 'required')
            ->setFormData($data)
            ->show(['material' => $material]);
    }

    /**
     * 新增动作响应
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function eventAdd(){
        $current_name = input('event', ReplyService::MSG);
        $builder = new FormBuilder();
        $data = [
            'bot_id' => $this->getCurrentBot('id'),
            'event' => $current_name,
            'status' => 1,
            'sort' => 1
        ];

        $builder->setPostUrl(url('savePost'))
            ->setTip("添加【".ReplyService::events($current_name)."】的响应动作")
            ->addFormItem('bot_id', 'hidden', 'botid', 'botid')
            ->addFormItem('event', 'hidden', 'event', 'event')
            ->addFormItem('msg_type', 'select', '消息类型', '接收到的消息类型', BotService::msgTypes())
            ->addFormItem('wxids', 'chosen_multi', '指定对象', '对指定好友或群起作用', FriendService::getWxidToNickname(), 'required')
            ->addFormItem('handle_type', 'select', '响应动作', '删除好友对私聊起作用，移出群对群聊起作用', ReplyService::actionTypes())
            ->addFormItem('sort', 'number', '排序', '数字越大优先级越高', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'], 'required')
            ->setFormData($data);

        return $builder->show();
    }

    /**
     * 编辑动作响应
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function eventEdit(){
        $bot = \request()->botInfo;
        $id = input('id', null);
        $reply = $this->model->where([
            $this->tenantWhere(),
            ['bot_id','=',$bot['id']]
        ])->find($id);

        if (!$reply) {
            return $this->error('参数错误!');
        }

        if(!empty($reply['wxids'])){
            $reply['wxids'] = explode(',', $reply['wxids']);
        }

        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('msg_type', 'select', '消息类型', '接收到的消息类型', BotService::msgTypes())
            ->addFormItem('wxids', 'chosen_multi', '指定对象', '对指定好友或群起作用', FriendService::getWxidToNickname(), 'required')
            ->addFormItem('handle_type', 'select', '响应动作', '删除好友对私聊起作用，移出群对群聊起作用', ReplyService::actionTypes())
            ->addFormItem('sort', 'number', '排序', '数字越大优先级越高', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'], 'required')
            ->setFormData($reply);

        return $builder->show();
    }
}